// SERVER AND BROWSESYNC
'use strict';

import gulp from 'gulp';
import {argv as args} from 'yargs';
import runSeq  from 'run-sequence';
import browserSync from 'browser-sync';


import messageLogger from '../utils/message.gulp';
import {routeProxy, serverProxy} from '../utils/middleware.rewrite.gulp';
import config  from '../gulp.config';


gulp.task('serve', (done) => {
    var preTask = args.dist ? 'dist' : 'build';
    runSeq(
        preTask,
        'watch',
        'browser-sync',
        done
    )
});

// BrowserSync
gulp.task('browser-sync', () => {
    if (browserSync.active) {
        return ;
    }

    var browser;
    var baseDir = args.dist ? config.dist : config.build;
    var open = 'external';

    var ghostMode = {
        clicks: true,
        location: false,
        forms: true,
        scroll: true
    }

    if (args.browserall) {
        if (isLinux()){
           browser = ['google-chrome','firefox', 'safari']; 
        } else {
            browser = ['google chrome','firefox', 'safari', 'internet explorer']; 
        }
    } else if (args.firefox){
        browser = ['firefox'];
    } else if (args.safari) {
        browser = ['safari'];
    } else {
        if (isLinux()){
           browser = ['google-chrome']; 
        } else {
            browser = ['google chrome']; 
        }
    }

    var options = {
        host: '127.0.0.1',
        port: 8000,
        server: {
            baseDir: baseDir,
            middleware: [
                routeProxy,
                serverProxy
            ]
        },
        ghostMode: args.browserall ? ghostMode: false,
        injectChanges: true,
        logFileChanges: true,
        logLevel: 'info',
        logPrefix: 'browser-sync',
        reloadDeley: 1000,
        browser: browser,
        open: args.noopen ? false : open
    };

    browserSync(options);

    function isLinux() {
        return process.platform === 'linux';
    }
});